package bearworker.zxl.config;

import javax.annotation.Resource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import java.sql.Connection;
import java.util.ArrayList;

/**
 * Created by 逍遥的熊 on 2017/11/16.
 */

@Configuration
@PropertySource(value = "classpath:${pro.env}/database.properties")
public class DatabaseConfig{

    @Resource
    private Environment environment;

    @Bean(name = "dataSource")
    public BasicDataSource dataSource(){
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUsername(environment.getRequiredProperty("database.username"));
        dataSource.setPassword(environment.getRequiredProperty("database.password"));
        dataSource.setUrl(environment.getRequiredProperty("database.url"));
        dataSource.setDriverClassName(environment.getRequiredProperty("database.driverClassName"));
        dataSource.setMaxIdle(environment.getRequiredProperty("database.maxIdle",Integer.class));
        dataSource.setMinIdle(environment.getRequiredProperty("database.minIdle",Integer.class));
        dataSource.setRemoveAbandonedTimeout(environment.getRequiredProperty("database.removeAbandonedTimeout",Integer.class));
        dataSource.setLogAbandoned(environment.getRequiredProperty("database.logAbandoned",Boolean.class));
        dataSource.setTestOnBorrow(environment.getRequiredProperty("database.testOnBorrow",Boolean.class));
        dataSource.setConnectionInitSqls(environment.getRequiredProperty("database.connectionInitSqls",ArrayList.class));
        return dataSource;
    }

    @Bean(name = "tx")
    public DataSourceTransactionManager tx(){
        return new DataSourceTransactionManager(this.dataSource());
    }
    
    @Bean(name = "sqlSessionFactoryBean")
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(this.dataSource());
        sessionFactory.setTypeAliasesPackage("bearworker.zxl.dao.mapper");
        return sessionFactory;
    }
    


    

}
